import { SCENARIO_TYPE } from '../const'

import config from '../config'
import bridge from '../bridge'

const COUNT_DOWN = 60
export default {
  data() {
    return {
      phone: '',
      password: '',
      code: '',
      countDown: '',
      SCENARIO_TYPE
    }
  },

  computed: {
    codeMsg() {
      if (this.countDown === COUNT_DOWN) {
        return '重新获取'
      }
      return `${this.countDown}s`
    }
  },

  methods: {
    startCountDown(time) {
      setTimeout(() => {
        this.countDown--
        if (this.countDown === 0) {
          this.countDown = COUNT_DOWN
        } else {
          this.startCountDown(1000)
        }
      }, time)
    },

    checkPhone() {
      if (!(/1\d{10}/g.test(this.phone.trim()))) {
        this.$toast('无效的手机号码')
        return false
      }
      return true
    },

    checkPassword() {
      if (!this.password.trim().length) {
        this.$toast('密码不能为空')
        return false
      } else if (this.password.trim().length < 5) {
        this.$toast('密码过于简单')
        return false
      }
      return true
    },

    getCode(code) {
      if (this.countDown && this.countDown < COUNT_DOWN) {
        return
      }
      this.countDown = COUNT_DOWN
      this.startCountDown(0)

      if (this.checkPhone()) {
        this.$get('sms/send', {
          phone: this.phone.trim(),
          code
        }).then(() => {
          this.$toast('验证码已发出')
        })
      }
    },

    onBack() {
    	if (this.config.env.isApp) {
    		this.action('goback')
    	} else {
    		history.back()
    	}
    },

    backLogin() {
      this.$router.replace('/login')
    }
  }
}
